import { getSongVkey, getLyrics } from 'api/song';
import { ERR_OK } from 'api/config';
// getSongURL,
export class Song {
  constructor ({id, mid, singer, name, album, duration, image, url,lyric,source}) {
    this.id = id;
    this.mid = mid;
    this.singer = singer;
    this.name = name;
    this.album = album;
    this.duration = duration;
    this.image = image;
	this.lyrics = lyric;
    if (url) {
      this.url = url;
    }
	this.source=source;
  }

  // 获取歌曲url的方法
  getSongUrl () {
    if (this.url) {
      return Promise.resolve(this.url);
    }
    console.log(this);
    return getSongVkey(this.mid).then((res) => {
          console.log(res);
          console.log(res.data.code);
      if (res.data.code === ERR_OK) {
        console.log(res.data.req_0.data);
        if (res.data.req.data.vkey) {
          let vkey = res.data.req.data.vkey;
          console.log(vkey);
          if (!vkey) { return Promise.reject(new Error('getSongKey function got vkey is null')); }
          let purl = res.data.req_0.data.midurlinfo[0].purl;
          if (purl) {
            let currentSongUrl = res.data.req_0.data.sip[0] + purl;
            this.url = currentSongUrl;
            console.log(currentSongUrl);
            return Promise.resolve(currentSongUrl);
          }
        }
      }
    }).catch((err) => {
      return Promise.reject(err);
    });
  }

  // 获取歌曲的歌词
  getLyrics () {
    if (this.lyrics) {
      return Promise.resolve(this.lyrics);
    }
    return getLyrics(this.id).then(res => {
      if (res && res.data.code === ERR_OK) {
        let lyrics = _decodeLyrics(res.data.lyric);
        this.lyrics = lyrics;
        return Promise.resolve(lyrics);
      }
    });
  }
}

function _decodeLyrics (lyrics) {
  return lyrics;
  // let div = document.createElement('div');
  // div.innerHTML = lyrics;
  // return div.innerHTML;
}

// 工厂方法，创建歌曲对象
export function createSong (musicData) {
	let id='';
	let singer='';
	let name='';
	let duration=0;
	let picUrl='';
	let url='';
	let lyricData='';
	let source='';
	var data= musicData.items.filter((item)=>{
		if(item.picUrl&&item.url){
			id=item.id;
			singer=item.singer;
			name=item.name;
			duration= item.duration;
			picUrl=item.picUrl;
			url=item.url;
			lyricData=item.lyricData;
			return item;
		}
	});
	
	source=musicData.source;
	
  return new Song({
    id: id,
    mid: id,
    singer: singer,
    name: name,
    album: musicData.album,
    duration: duration,
    image: picUrl, 
	url:url,
	lyric:lyricData,
	source:source
  });
}

// 如果有多个歌手名，则用/隔开
export function filterSinger (singer) {
  let ret = [];
  singer.forEach(s => ret.push(s.name));
  return ret.join('/');
}
